package com.william.jdbcplus.core.condition.segment.impl;

import com.william.jdbcplus.core.enums.SqlKeyword;
import com.william.jdbcplus.core.toolkit.StringPool;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * From SQL 片段
 * from 到 where 之间部分
 *
 * @author niliwei
 */
public class FromSegmentList extends AbstractSegmentList {

    @Override
    public boolean add(String segment) {
        if (this.contains(segment)) {
            return true;
        }

        return super.add(segment);
    }

    @Override
    public String getSegment() {
        if (isEmpty()) {
            return StringPool.EMPTY;
        }

        // from table 列表
        List<String> fromList = new ArrayList<>();
        // join table 列表
        List<String> joinList = new ArrayList<>();
        for (String item : this) {
            boolean matchJoin = item.trim().startsWith(SqlKeyword.JOIN.getSegment() + StringPool.SPACE);
            boolean matchInnerJoin = item.trim().startsWith(SqlKeyword.INNER_JOIN.getSegment() + StringPool.SPACE);
            boolean matchLeftJoin = item.trim().startsWith(SqlKeyword.LEFT_JOIN.getSegment() + StringPool.SPACE);
            boolean matchRightJoin = item.trim().startsWith(SqlKeyword.RIGHT_JOIN.getSegment() + StringPool.SPACE);
            boolean matchFullJoin = item.trim().startsWith(SqlKeyword.FULL_JOIN.getSegment() + StringPool.SPACE);
            if (!matchJoin && !matchInnerJoin && !matchLeftJoin && !matchRightJoin && !matchFullJoin) {
                fromList.add(item);
            } else {
                joinList.add(item);
            }
        }

        String fromSegment = fromList.stream().collect(Collectors.joining(StringPool.COMMA));
        String joinSegment = joinList.stream().collect(Collectors.joining(StringPool.SPACE));

        if (joinSegment.equals(StringPool.EMPTY)) {
            return fromSegment;
        }

        return fromSegment + StringPool.SPACE + joinSegment;
    }

    @Override
    public String getSql() {
        if (isEmpty()) {
            return StringPool.EMPTY;
        }
        return StringPool.SPACE + SqlKeyword.FROM.getSegment() + StringPool.SPACE + getSegment();
    }
}
